package com.vm.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.vm.commons.CurrentUser;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.fragment.UIHelper;
import com.vm.utils.MyDisplayImageOptions;
import com.vm.utils.UploadUtil;
import com.wwtscapp.apk.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class PersonActivity extends Activity {
	ImageView imageView1;
	LinearLayout layout_user_head;
	LinearLayout layout_username;
	LinearLayout layout_change_password;
	ImageView imgbtn_back;
	TextView tv_username;
	TextView tv_telephone;
	private Uri photoUri;
	private Uri logoUri;
	private final int PIC_FROM_CAMERA = 1;
	private final int PIC_FROM＿LOCALPHOTO = 0;
	String status;
	Timer timer;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_edit);
		imageView1 = (ImageView) findViewById(R.id.imageView1);
		// if
		File file = new File(StringUtil.getFilePath());
		if (!file.exists()) {
			file.mkdirs();
		}
		File logoFile = new File(file, "logo.jpeg");
		if (!logoFile.exists()) {
			if (CurrentUser.IMAGEURL != null) {
				ImageLoader.getInstance().displayImage(
						VMConst.URL + CurrentUser.IMAGEURL, imageView1,
						MyDisplayImageOptions.getInstance());
			} else {
				imageView1.setImageResource(R.drawable.bg_photo);
			}
		} else {
			logoUri = Uri.fromFile(logoFile);
			Bitmap bitmap = decodeUriAsBitmap(logoUri);
			imageView1.setImageBitmap(bitmap);
		}

		init();
	}

	public void onResume() {
		init();
		super.onResume();
	}

	public void init() {
		imgbtn_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		imgbtn_back.setOnClickListener(btn_clicklistener);
		layout_user_head = (LinearLayout) findViewById(R.id.layout_user_head);
		layout_username = (LinearLayout) findViewById(R.id.layout_username);
		layout_change_password = (LinearLayout) findViewById(R.id.layout_change_password);
		layout_username.setOnClickListener(btn_clicklistener);
		layout_change_password.setOnClickListener(btn_clicklistener);
		layout_user_head.setOnClickListener(photo_Listener);
		tv_username = (TextView) findViewById(R.id.tv_username);
		tv_telephone = (TextView) findViewById(R.id.tv_telephone);
		tv_username.setText(CurrentUser.NICKNAME);
		tv_telephone.setText(CurrentUser.PHONNE);
	}

	OnClickListener btn_clicklistener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent;
			switch (v.getId()) {
			case R.id.imgbtn_search_back:
				onBackPressed();
				break;
			case R.id.layout_change_password:
				intent = new Intent(PersonActivity.this,
						ChangePsdActivity.class);
				startActivity(intent);
				break;
			case R.id.layout_username:
				intent = new Intent(PersonActivity.this,
						ChangeNickNameActivity.class);
				startActivity(intent);
				break;
			default:
				break;
			}
		}

	};
	OnClickListener photo_Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			final CharSequence[] items = { "相机拍照", "本地图片" };
			AlertDialog.Builder builder = new AlertDialog.Builder(
					PersonActivity.this);
			builder.setCancelable(true);
			builder.setItems(items, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					if (which == 0) {
						doHandlerPhoto(PIC_FROM_CAMERA);// 用户点击了从照相机获取
					}
					if (which == 1) {
						doHandlerPhoto(PIC_FROM＿LOCALPHOTO);// 从相册中去获取
					}
				}

			});
			AlertDialog alert = builder.create();
			alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
			alert.show();
		}

	};

	/**
	 * 根据不同方式选择图片设置ImageView
	 * 
	 * @param type
	 *            0-本地相册选择，非0为拍照
	 */
	private void doHandlerPhoto(int type) {
		try {
			// 保存裁剪后的图片文件
			File pictureFileDir = new File(StringUtil.getFilePath());
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			}
			File picFile = new File(pictureFileDir, "logo.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);

			if (type == PIC_FROM＿LOCALPHOTO) {
				Intent intent = getCropImageIntent();
				startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
			} else {
				Intent cameraIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(cameraIntent, PIC_FROM_CAMERA);
			}

		} catch (Exception e) {
			Log.i("HandlerPicError", "处理图片出现错误");
		}
	}

	/**
	 * 调用图片剪辑程序
	 */
	public Intent getCropImageIntent() {
		Intent intent = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		intent.setType("image/*");
		setIntentParams(intent);
		return intent;
	}

	/**
	 * 启动裁剪
	 */
	private void cropImageUriByTakePhoto() {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		setIntentParams(intent);
		startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
	}

	/**
	 * 设置公用参数
	 */
	private void setIntentParams(Intent intent) {
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 600);
		intent.putExtra("outputY", 600);
		intent.putExtra("noFaceDetection", true); // no face detection
		intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		intent.putExtra("scaleUpIfNeeded", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PIC_FROM_CAMERA: // 拍照
			try {
				cropImageUriByTakePhoto();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case PIC_FROM＿LOCALPHOTO:
			try {
				if (photoUri != null) {
					Bitmap bitmap = decodeUriAsBitmap(photoUri);
					// String path = StringUtil.getFilePath();
					// File dirFile = new File(path);
					// if (!dirFile.exists()) {
					// dirFile.mkdir();
					// }
					File myCaptureFile = new File(photoUri.getPath());
					BufferedOutputStream bos = new BufferedOutputStream(
							new FileOutputStream(myCaptureFile));
					bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
					bos.flush();
					bos.close();
					String fileName = UUID.randomUUID().toString();
					imageView1.setImageBitmap(bitmap);
					status = UploadUtil.uploadFile(myCaptureFile, fileName);
					UIHelper.showDialogForLoading(PersonActivity.this,
							"头像上传存在一定延迟...", true);
					timer = new Timer(true);
					timer.schedule(task, 4000, 1000);
					// while (status.contains("ok")) {
					// Toast toast = Toast.makeText(PersonActivity.this,
					// "头像上传成功", Toast.LENGTH_SHORT);
					// toast.show();
					// }
					// CurrentUser.IMAGEURL = StringUtil.getDateDir("logo")
					// + fileName + ".png";
					// luidao.updateLogo();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}

	TimerTask task = new TimerTask() {
		public void run() {
			Looper.prepare();
			timer.cancel();
			UIHelper.hideDialogForLoading();
		}
	};

	private Bitmap decodeUriAsBitmap(Uri uri) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}

	public void onBackPressed() {
		super.onBackPressed();
		System.out.println("按下了back键   onBackPressed()");
	}
}
